package com.wanggsx.library.util.fun.download;

import com.wanggsx.library.util.UtilsFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by wanggsx on 15/12/23.
 */
public class DownloadManager {

    public static void download(final String fileUrl, final String filePath, final boolean replaceIfExisted, final DownloadCallback callback) {
        if (!replaceIfExisted && filePath != null && new File(filePath).exists()) {
            callback.onFinish(true, filePath);
            return;
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (filePath == null) {
                        String strFile = UtilsFile.getAutoFileDirectory() + "download/" + UtilsFile.getFileNameFromPath(fileUrl);
                        downloadFile(fileUrl, strFile, replaceIfExisted, callback);
                    } else {
                        downloadFile(fileUrl, filePath, replaceIfExisted, callback);
                    }
                }
            }).start();
        }
    }

    static boolean downloadFile(String urlStr, String path, boolean replaceIfExisted, DownloadCallback callback) {
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            // 构造URL
            URL url = new URL(urlStr);
            // 打开连接
            URLConnection con = url.openConnection();
            //获得文件的长度
            int contentLength = con.getContentLength();
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File file = new File(path);
            if (file.exists()) {
                if (replaceIfExisted) {
                    file.delete();
                } else {
                    return true;
                }
            }
            UtilsFile.mkdirs(path);
            file.createNewFile();//新建文件
            os = new FileOutputStream(file);
            callback.onProcess(0, contentLength);
            // 开始读取
            int i = 0;
            int arg = 0;
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
                i += len;
                if (callback != null) {
                    callback.onProcess(i, contentLength);
                }
            }
            if (callback != null) {
                callback.onFinish(true, path);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
